package com.vitaf.cash.app.ui.dialog

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import androidx.core.graphics.toColorInt
import androidx.core.net.toUri
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.vitaf.cash.app.R
import com.vitaf.cash.app.base.app.VitafActStackManager
import com.vitaf.cash.app.common.VitafComDlog
import com.vitaf.cash.app.databinding.DataBindingHelper
import com.vitaf.cash.app.databinding.VitafDlogCustomerBinding
import com.vitaf.cash.app.event.VitafEventPointType
import com.vitaf.cash.app.ui.activity.VitafUserAdviceTypeAct
import com.vitaf.cash.app.ui.adapter.VitafCustomerApt
import com.vitaf.cash.app.utils.SpannableStringUtil
import com.vitaf.cash.app.utils.helper.VitafConfigsHp
import com.vitaf.cash.app.utils.shared.VitafSharedHp
import com.vitaf.cash.app.utils.shared.VitafSharedKey
import com.vitaf.cash.lib.adapter.VitafOnItemChildClickListener
import org.json.JSONObject

/**
 * VitafCash
 * @Author wwdeng
 * @CreateTime: 2024/11/15 10:29
 * @Annotation：联系客服Dialog
 */
class VitafCustomerDlog(context: Context) : VitafComDlog(context) {
    lateinit var binding: VitafDlogCustomerBinding
    private var callback: IDialogCallback? = null
    //客服联系方式列表
    private var customerAdapter: VitafCustomerApt? = null

    private var viewModel = DataBindingHelper.createModel()

    override val pageName: String = "Customer_Service"

    override fun initializeVitafWindow() {
        val params = window?.attributes
        params?.width = WindowManager.LayoutParams.MATCH_PARENT
        params?.height = WindowManager.LayoutParams.WRAP_CONTENT
        window?.attributes = params
//        window?.setWindowAnimations(android.R.style.Animation_InputMethod) //修改动画样式
        window?.setWindowAnimations(R.style.dialog_slide_anim) //修改动画样式
        window?.setGravity(Gravity.BOTTOM)
    }

    override fun createVitafContentView(): View {
        binding = VitafDlogCustomerBinding.inflate(LayoutInflater.from(context))
        return binding.root
    }

    override fun initializeVitafViews() {
        binding.model = viewModel
        binding.dialogCustomer = this
//        binding.lifecycleOwner = this
        initGombeCreditCustomerListView()
    }

    override fun setupVitafEventListeners() {
    }

    override fun loadVitafData() {
        val isLogin = VitafSharedHp.takeGombeCreditSharedBoolean(VitafSharedKey.GOMBECREDIT_LOGIN)
        viewModel.set("isLogin",isLogin)

        setGombeCreditCustomerContactData()
    }

    override fun onVitafEventViewClick(v: View?) {
    }

    /**
     * 关闭
     */
    fun onCustomerClickClose(){
        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.CUSTOMER_CLOSE, eventRemark = pageRemark)
        dismiss()
    }

    /**
     * 意见反馈
     */
    fun onCustomerClickFeedback(){
        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.CUSTOMER_FEEDBACK,pageRemark)
        dismiss()
        onGombeCreditCustomerFeedbackAction()
    }

    /**
     * 事件备注
     */
    fun setGombeCreditCustomerEventRemark(remark: String): VitafCustomerDlog {
        this.pageRemark = remark
        return this
    }

    /**
     * 设置监听回调
     */
    fun setGombeCreditCustomerClickCallback(callback: IDialogCallback): VitafCustomerDlog {
        this.callback = callback
        return this
    }

    fun setGombeCreditCustomerCancelable(flag: Boolean): VitafCustomerDlog {
        setCancelable(flag)
        return this
    }

    fun setGombeCreditCustomerCanceledOnTouchOutside(flag: Boolean): VitafCustomerDlog {
        setCanceledOnTouchOutside(flag)
        return this
    }

    /**
     * 初始化客服联系方式列表
     */
    private fun initGombeCreditCustomerListView() {
        binding.dialogCustomerWorkTimeText.visibility = View.GONE
        binding.dialogCustomerItemListview.visibility = View.GONE
        binding.dialogCustomerItemListview.layoutManager = LinearLayoutManager(context)
        customerAdapter = VitafCustomerApt(binding.dialogCustomerItemListview)
        binding.dialogCustomerItemListview.adapter = customerAdapter
        binding.dialogCustomerItemListview.itemAnimator = DefaultItemAnimator()
        customerAdapter?.setOnItemChildClickListener(VitafOnItemChildClickListener { _, childView, position ->
            if (childView.id == R.id.textCustomerFun) {
                customerAdapter?.let {
                    val item = it.getItem(position)
                    when (item.optString("type")) {
                        "MOBILE" -> {//电话
                            callback?.onGombeCreditCallPhoneClick(item.optString("value"))
                            onGombeCreditCustomerMobileCallAction(item.optString("value"))
                        }

                        else -> {//邮箱
                            callback?.onGombeCreditCopyEmailClick(item.optString("value"))
                        }
                    }
                }
            }
        })
    }

    /**
     * 获取联系方式列表
     */
    @SuppressLint("SetTextI18n")
    private fun setGombeCreditCustomerContactData(){
        binding.dialogCustomerWorkTimeText.visibility = View.VISIBLE
        binding.dialogCustomerItemListview.visibility = View.VISIBLE
        val contactList = arrayListOf<JSONObject>()
        val customize = VitafConfigsHp.takeGombeCreditConfigData()
        customize?.let {
            if (it.optString("mobile","").isNotEmpty()){
                val mobileList = it.optString("mobile").split(",")
                for (i in mobileList.indices){
                    val obj = JSONObject()
                    obj.put("type","MOBILE")
                    obj.put("value", mobileList[i])
                    contactList.add(obj)
                }
            }

            if (it.optString("email","").isNotEmpty()){
                val emailList = it.optString("email").split(",")
                for (i in emailList.indices){
                    val obj = JSONObject()
                    obj.put("type","EMAIL")
                    obj.put("value", emailList[i])
                    contactList.add(obj)
                }
            }
        }
        customerAdapter?.data = contactList

        //工作时间
        var workDate = ""
        var workTime = ""
        customize?.let {
            val customData = it.optJSONObject("customData")
            customData?.let {
                workDate = customData.optString("workDate")
                workTime = customData.optString("workTime")
            }
        }
        val workText = SpannableStringUtil.create()
            .setText(String.format(getString(R.string.dialog_customer_time), "$workDate,$workTime."))
            .setKey("$workDate,")
            .setColor("#999999".toColorInt())
            .complete()
            .setKey("$workTime.")
            .setColor("#666666".toColorInt())
            .complete()
            .build()
        binding.dialogCustomerWorkTimeText.text = workText
    }

    /**
     * 拨号
     */
    private fun onGombeCreditCustomerMobileCallAction(mobile: String){
        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.CUSTOMER_DIAL, "Mobile ：$mobile")
        val callIntent = Intent(Intent.ACTION_DIAL)
        callIntent.data = "tel:$mobile".toUri()
        context.startActivity(callIntent)
    }

    /**
     * feedback
     */
    private fun onGombeCreditCustomerFeedbackAction(){
        //当前栈顶是 意见反馈类型
        if (VitafActStackManager.isCurrentActivity(VitafUserAdviceTypeAct::class.java)){
            return
        }
        val intent = Intent(context, VitafUserAdviceTypeAct::class.java)
        context.startActivity(intent)
    }

    interface IDialogCallback {
        //拨号
        fun onGombeCreditCallPhoneClick(phoneNumber: String)
        //Copy
        fun onGombeCreditCopyEmailClick(email: String)
        //feedback
        fun onGombeCreditFeedbackClick()
    }
}